/**
 * 
 */
package cn.telling.productapprove.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.telling.common.exception.BusinessException;
import cn.telling.common.pager.PageVo;
import cn.telling.common.tools.message.service.IMessageInfoService;
import cn.telling.common.tools.message.util.MessageConstantValues;
import cn.telling.common.tools.message.vo.MessageInfoVo;
import cn.telling.common.util.MessageCode;
import cn.telling.common.util.TellingConstance;
import cn.telling.common.vo.LoginingVo;
import cn.telling.product.service.ISupplyService;
import cn.telling.product.vo.SupplyVo;
import cn.telling.productapprove.dao.IProductApproveDao;
import cn.telling.productapprove.service.IProductApproveService;
import cn.telling.productapprove.vo.ConditionApproveVo;
import cn.telling.productapprove.vo.ProductApproveVo;
import cn.telling.productapprove.vo.ProductBidApproveVo;
import cn.telling.productapprove.vo.ShopProductVO;

/**
 * @Title: ProductApproveServiceImpl.java
 * @Package com.productapprove.service.impl
 * @Description: 商品审批处理相关业务逻辑Service实现
 * @author guohui
 * @date 2013-4-26 上午9:13:41
 * @version V1.0
 */
@Service("ProductApproveService")
public class ProductApproveServiceImpl implements IProductApproveService {

	@Autowired
	@Qualifier("ProductApproveDao")
	private IProductApproveDao productApproveDao;

	@Autowired
	@Qualifier("messageInfoService")
	private IMessageInfoService messageInfoService;
	
	@Autowired
	private ISupplyService supplyService;

	public IMessageInfoService getMessageInfoService() {
		return messageInfoService;
	}

	public void setMessageInfoService(IMessageInfoService messageInfoService) {
		this.messageInfoService = messageInfoService;
	}
	
	/*@Autowired
	@Qualifier("supplyService")
	private ISupplyService supplyService;*/
	//到货通知
	/*@Autowired
	@Qualifier("ArrivalNoticeService")
	private IArrivalNoticeService arrivalNoticeService;*/

	@Override
	public List<ProductApproveVo> GetByPage(ConditionApproveVo condition,
			PageVo pageVo,LoginingVo loVo) {
		return productApproveDao.GetByPage(condition, pageVo,loVo);
	}

	@Override
	public int GetTotalCount(ConditionApproveVo condition,LoginingVo loVo) {
		return productApproveDao.GetTotalCount(condition,loVo);
	}
	
	@Override
	public ProductApproveVo GetApproveInfoById(String approveId) {
		return productApproveDao.GetApproveInfoById(approveId);
	}
	
	@Override
	public ProductApproveVo GetApproveInfoBySupplyAreaId(String supplyAreaId) {
		return productApproveDao.GetApproveInfoBySupplyAreaId(supplyAreaId);
	}
	
	@Override
	@Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	public int Approve(ProductApproveVo productApproveVo) {
		
		ProductApproveVo approveVo = productApproveDao.GetApproveInfoById(productApproveVo.getId());
		
		ProductApproveVo paraVo = new ProductApproveVo();
		paraVo.setId(approveVo.getId());
		paraVo.setSupplyAreaId(approveVo.getSupplyAreaId());
		//paraVo.setShopProductId(approveVo.getShopProductId());
		//paraVo.setAreaId(approveVo.getAreaId());
		//paraVo.setSaleStatus(productApproveVo.getApproveStatus());
		paraVo.setApproveStatus(productApproveVo.getApproveStatus());
		paraVo.setApproveUser(productApproveVo.getApproveUser());
		
		String msg = "";
		if (TellingConstance.SALESTATUS3.equals(productApproveVo.getApproveStatus())) {
			msg = "审核通过！";
			// 通过申请
			if ("0".equals(approveVo.getSaleStatus())) {
				// 非申请上下架
				paraVo.setPriceAfter(approveVo.getPriceAfter());
				paraVo.setStockAfter(approveVo.getStockAfter());
				
				// 价保处理
				BigDecimal priceBefore = new BigDecimal(approveVo.getPriceBefore());
				BigDecimal priceAfter = new BigDecimal(approveVo.getPriceAfter());
				if (priceAfter.compareTo(priceBefore) < 0) {
					
				}
				//到货通知
				BigDecimal storenumBefore = new BigDecimal(approveVo.getStockBefore());
				BigDecimal storenumAfter = new BigDecimal(approveVo.getStockAfter());
				if (storenumBefore.compareTo(storenumAfter) < 0) {
//					this.getArrivalNoticeService().sendMsgAndEmail(approveVo.getShopProductId(), approveVo.getAreaId(), approveVo.getCustId());
				}
			} else {
				paraVo.setPriceAfter(approveVo.getPriceAfter());
				paraVo.setStockAfter(approveVo.getStockAfter());
				//到货通知
				BigDecimal storenumBefore = new BigDecimal(approveVo.getStockBefore());
				BigDecimal storenumAfter = new BigDecimal(approveVo.getStockAfter());
				if (storenumBefore.compareTo(storenumAfter) < 0) {
//					this.getArrivalNoticeService().sendMsgAndEmail(approveVo.getShopProductId(), approveVo.getAreaId(), approveVo.getCustId());
				}
				// 申请上下架
				if (TellingConstance.SALETYPE1.equals(approveVo.getSaleType())) {
					// 竞价发布
					String continuous = approveVo.getSaleStatus();
					if ("2".equals(continuous)) {
						continuous = "1";
					} else {
						continuous = "0";
					}
					paraVo.setContinuous(continuous);
				} else {
					// 其他情况
					String status = null;
					if ("1".equals(approveVo.getSaleStatus())) {
						// 申请下架
						status = "2";
					} else {
						// 申请上架
						status = "1";
					}
					paraVo.setStatus(status);
				}
			}
		} else if (TellingConstance.SALESTATUS2.equals(productApproveVo.getApproveStatus())) {
			// 不通过申请
			msg = "审核未通过！";
			if ("2".equals(approveVo.getSaleStatus())) {
				// 申请上架失败改为下架状态
				paraVo.setStatus("2");
			}
		}else if(TellingConstance.SALESTATUS4.equals(productApproveVo.getApproveStatus())){
			
			// 二审中
				msg = "二审中！";
				if ("2".equals(approveVo.getSaleStatus())) {
					// 申请上架失败改为下架状态
					//paraVo.setStatus("2");
				}
		}
		
		int i = productApproveDao.UpdateSupplyArea(paraVo);
		if(i==0){
			throw new BusinessException(BusinessException.TYPE_BACK, MessageCode.MSG_INFO_0039);
		}
		int num = productApproveDao.UpdateApprove(paraVo);
		
		
		
		//天音自有产品（含集采、分采）进行非定向发布,系统自动审核通过，不发送站内信（王震）
		if( null != productApproveVo.getIsSysApprove() && !"1".equals(productApproveVo.getIsSysApprove())){
		 MessageInfoVo vo = new MessageInfoVo();
		 vo.setDetail_id(new BigDecimal(approveVo.getSupplyAreaId()));//detail_id 可以是订单号，可以是产品ID
		 vo.setSend_user_id(new BigDecimal(productApproveVo.getApproveUser()));//send_user_id 是消息发起人
		 /*SupplyVo supplyVo = supplyService.findSupplyBySupplyId(approveVo.getSupplyId());
		 if (supplyVo != null) {
			vo.setTo_user_id(supplyVo.getUser_id());//to_user_id 是消息对应人
		 }*/
		 vo.setMessage_memo(approveVo.getRemark() + "\r\n" + msg);//message_memo为消息内容，具体内容格式由业务提供
		 vo.setMessage_type(MessageConstantValues.MESSAGE_TYPE_04);//消息类型，如有需要可在MessageConstantValues文件下新增消息类型，比如MESSAGE_TYPE_02代表发货提醒
		 messageInfoService.insertMessageInfo(vo);
	   }
		
		 return num;

	}

	/*@Override
	public List<SupplyVo> getSupplyName() {
		return productApproveDao.getSupplyName();
	}*/

	@Override
	public int GetBidTotalCount(ConditionApproveVo condition) {
		return productApproveDao.GetBidTotalCount(condition);
	}

	@Override
	public List<ProductBidApproveVo> GetBidByPage(ConditionApproveVo condition,
			PageVo pageVo) {
		return productApproveDao.GetBidByPage(condition, pageVo);
	}
	
	@Override
	public List<ProductApproveVo> GetBidApproveInfo(String productId, String areaId) {
		return productApproveDao.GetBidApproveInfo(productId, areaId);
	}
	
	@Override
	@Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	public int BidApprove(ProductApproveVo productApproveVo) {
		
		List<ProductApproveVo> productApproveVoList = productApproveDao.GetBidApproveInfo(productApproveVo.getId(), productApproveVo.getAreaId());
		
		for(int i = 0; i < productApproveVoList.size(); i++) {
			ProductApproveVo approveVo = productApproveVoList.get(i);
			
			String msg = "";
			if (approveVo.getSupplyAreaId().equals(productApproveVo.getSupplyAreaId())) {
				productApproveDao.UpdateBidApproveSucc(approveVo);
				msg = "竞价成功！";
			} else {
				productApproveDao.UpdateBidApproveFail(approveVo);
				msg = "竞价失败！";
			}
			
			MessageInfoVo vo = new MessageInfoVo();
			vo.setDetail_id(new BigDecimal(approveVo.getSupplyAreaId()));//detail_id 可以是订单号，可以是产品ID
			vo.setSend_user_id(new BigDecimal(productApproveVo.getApproveUser()));//send_user_id 是消息发起人
			/*SupplyVo supplyVo = supplyService.findSupplyBySupplyId(approveVo.getSupplyId());
			if (supplyVo != null) {
				vo.setTo_user_id(supplyVo.getUser_id());//to_user_id 是消息对应人
			}*/
			vo.setMessage_memo(msg);//message_memo为消息内容，具体内容格式由业务提供
			vo.setMessage_type(MessageConstantValues.MESSAGE_TYPE_04);//消息类型，如有需要可在MessageConstantValues文件下新增消息类型，比如MESSAGE_TYPE_02代表发货提醒
			int num = messageInfoService.insertMessageInfo(vo); 
		}

		return productApproveVoList.size();
	}

	/*@Override
	public List<SupplyVo> getTySupplyName() {
		return productApproveDao.getTySupplyName();
	}*/

	@Override
	public int GetTotalCountbyType(ConditionApproveVo condition, LoginingVo loVo,String Type) {
		return productApproveDao.GetTotalCount(condition,loVo,Type);
	}

	@Override
	public List<ProductApproveVo> GetByPagebyType(ConditionApproveVo condition,
			PageVo pageVo, LoginingVo loVo, String Type) {
		return productApproveDao.GetByPage(condition, pageVo,loVo,Type);
	}
	/*@Override
	public List<SupplyVo> getFirmSupplyName(){
		return productApproveDao.getFirmSupplyName();
	}*/
	@Override
	public List<ProductApproveVo> GetByPage4Firm(ConditionApproveVo condition ,PageVo pageVo){
		return productApproveDao.GetByPage4Firm(condition, pageVo);
	}
	@Override
	public int GetTotalCount4Firm(ConditionApproveVo condition){
		return productApproveDao.GetTotalCount4Firm(condition);
	}
	@Override
	public List<ProductApproveVo> GetApproveListById(String approveId){
		return productApproveDao.GetApproveListById(approveId);
	}
	/**
	 * 供应商是否有发布中的产品
	 * @param supplyId
	 * @return
	 */
	@Override
	public boolean hasPublichBySupply(BigDecimal supplyId){
		if(supplyId==null){
			return false;
		}
		int i = productApproveDao.publichNumBySupply(supplyId);
		if(i>0) return true;
		else return false;
	}

	@Override
	public BigDecimal findApproveId() {
		// TODO Auto-generated method stub
		return productApproveDao.findApproveId();
	}

	@Override
	public int ApproveToSecond(ProductApproveVo productApproveVo) {
		// TODO Auto-generated method stub
		return  productApproveDao.UpdateApprove(productApproveVo);
	}

	@Override
	public List<ProductApproveVo> getSupplyAreaId(String shopProductIds) {
		return  productApproveDao.getSupplyAreaId(shopProductIds);
	}


	@Override
	public int updateGiftsFapiao(String gifts, String isfapiao,
			String supplyAreaId) {
		// TODO Auto-generated method stub
		return 	productApproveDao.updateGiftsFapiao(gifts, isfapiao, supplyAreaId);
	
	}
	
	//县包指定供应商，审核数据
	@Override
	public boolean assignProductCountry(String userid, List<String> productIds) {
		//保存供应商产品
		boolean flag =true;
		/*int  a=0;
		try{
			if(!"".equals(userid)){
				ShopProductVO spv=new ShopProductVO();
				SupplyVo svo=supplyService.findSupplyByUserId(userid);
				String supplyType=svo.getSupply_type();
				if(supplyType.equals(TellingConstance.supply_type03)||supplyType.equals(TellingConstance.supply_type04)){
					BigDecimal supplyid= svo.getId();
					//supplyService.findSupplyByUserId(userid).getId();
					spv.setSupplyId(supplyid);
					spv.setIsValid(TellingConstance.IS_VALID_01);
					spv.setDelflag(TellingConstance.DEL_FLAG_1);
					spv.setSaleMode(TellingConstance.APPOINTMODE);
					spv.setStatus(TellingConstance.ASSIGNEDAPPROVE);
					if(productIds!=null&&productIds.size()>0){
						for(String  productid:productIds){
							spv.setProductId(productid==null?new BigDecimal(""):new BigDecimal(productid));
							//判断产品是否以及指定给该供应商
							ShopProductVO tempVo=new ShopProductVO();
							tempVo=productApproveDao.queryProductTempCountry(spv);
							if(tempVo.getShopProductId()==null){//没有指定
							a=	productApproveDao.updateProductCountry(spv, "1",supplyType);
							}else{
								String str=productApproveDao.queryProductCountry(tempVo.getShopProductId().toString());
								if("".equals(str)){//审核正式表没有数据时
								a=	productApproveDao.updateProductCountry(spv, "0",supplyType);
								}
							}
						} 
					}
					if(a>0){
						  flag=true;	
						}else{
						  flag=false;
						}
				}else{
					flag=false;
				}
			}else{
				flag=false;
			}
		}catch(Exception e){
			e.printStackTrace();
			flag=false;
		}*/
		return flag;
	}


}
